from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from .serializers import *
import re


# 产品信息
class GoodsView(APIView):

    def get(self,request):
        # 0 接受uid   1
        uid = request.GET.get("uid","")
        # 1 获取虽有的商品
        if uid:
            data = []
            goodsqueryset = models.Goods.objects.all()
            for i in goodsqueryset:
                dict = ({"id":i.id,"title":i.title,"img":str(i.img),"price1":i.price2})
                data.append(dict)
            return Response(data)
        else:
            goodsqueryset = models.Goods.objects.all()
            # 2 序列化
            obj = Gooserializer(goodsqueryset,many=True)
            return Response(obj.data)


# 登录
class LoginView(APIView):

    def post(self,request):
        # 1 接受参数
        username = request.data.get("username")
        password = request.data.get("password")

        # 2 查库判断
        userobj = models.User.objects.filter(username=username,password=password).first()
        if userobj:
            return Response({"code":1000,"msg":"登录成功","data":userobj.id})
        return Response({"code":1001,"msg":"用户名或者密码错误","data":""})


# 订单
class OrderView(APIView):
    # 获取某人的订单
    def get(self,request):
        # 1 接收参数
        uid = request.GET.get("uid")

        # 2 查询订单
        orderqueryset = models.Order.objects.filter(user_id=uid).all()

        # 3 序列化
        obj = Orderserializer1(orderqueryset,many=True)
        return Response(obj.data)
        pass



    # 添加
    def post(self,request):
        # 1 接收参数
        uid = request.data.get("uid")
        goodid = request.data.get("goodid")
        name = request.data.get("name")
        phone = request.data.get("phone")

        # 2 正则判断
        if not name:
            return Response({"code":1001,"msg":"姓名不能为空"})

        if not re.match(r'^1[3-9]{1}\d{9}$',phone):
            return Response({"code": 1002, "msg": "手机号不合法"})


        # 3 构造数据
        data = {
            "user":uid,
            "goods":goodid,
            "name":name,
            "phone":phone
        }

        # 4 反序列化
        obj = Orderserializer(data=data)

        # 5 判断
        if obj.is_valid():
            obj.save()
            return Response({"code": 1000, "msg": "订单添加成功"})

        # 6 打印
        print(obj.errors)

        # 7 返回
        return Response({"code": 1003, "msg": "参数有误"})
